package com.pinoc.demo.service.es.impl;

import com.pinoc.demo.common.es.EsRestHighLevelClient;
import com.pinoc.demo.service.es.EsOperateService;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author yinpeng
 */
@Service
public class EsOperateServiceImpl implements EsOperateService {

	@Resource(name = "esRestHighLevelClient")
	private EsRestHighLevelClient esRestHighLevelClient;

	@Override
	public void upsert(String indexName, String documentId, XContentBuilder content) {
		try {
			RestHighLevelClient client = esRestHighLevelClient.getClient();
			// update and insert
			UpdateRequest request = new UpdateRequest(indexName, documentId).doc(content).upsert(content);
			UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean existIndex(String indexName) throws IOException {
		RestHighLevelClient client = esRestHighLevelClient.getClient();
		GetIndexRequest request = new GetIndexRequest(indexName);
		return client.indices().exists(request, RequestOptions.DEFAULT);
	}

	@Override
	public GetResponse getById(String indexName, String id) throws IOException {
		SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
		searchBuilder.query(QueryBuilders.termQuery("customer_id", id));
		GetRequest request = new GetRequest(indexName).id(id);
		GetResponse documentFields = esRestHighLevelClient.getClient().get(request, RequestOptions.DEFAULT);
		return documentFields;
	}
}
